package com.example.qu_tao.View;

import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.qu_tao.R;
import com.example.qu_tao.database.DBHelper;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class XieWenZhangActivity extends AppCompatActivity {

    private EditText etContent;
    private TextView tvPublish;
    private ImageButton btnBack;
    private DBHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xiewenzhang);
        dbHelper = new DBHelper(this);

        initViews();
        setupClickListeners();
    }

    private void initViews() {
        etContent = findViewById(R.id.et_content);
        tvPublish = findViewById(R.id.tv_publish);
        btnBack = findViewById(R.id.btn_back);
    }

    private void setupClickListeners() {
        // 返回按钮点击事件
        btnBack.setOnClickListener(v -> showExitConfirmationDialog());

        // 发布按钮点击事件
        tvPublish.setOnClickListener(v -> {
            String content = etContent.getText().toString().trim();
            if (TextUtils.isEmpty(content)) {
                Toast.makeText(this, "请输入文章内容", Toast.LENGTH_SHORT).show();
                return;
            }
            publishArticle(content);
        });
    }

    private void publishArticle(String content) {
        String currentTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(new Date());
        int userId = 1; // 示例用户ID，实际应从登录状态获取

        // 使用SQLiteDatabase直接插入数据（确保时间精度）
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        try {
            db.beginTransaction(); // 开启事务

            ContentValues values = new ContentValues();
            values.put("user_id", userId);
            values.put("content", content);
            values.put("post_type", 1); // 1表示文章
            values.put("image_paths", ""); // 文章无图片
            values.put("create_time", currentTime); // 显式设置带秒的时间

            long postId = db.insert("posts", null, values);
            if (postId != -1) {
                db.setTransactionSuccessful(); // 标记事务成功
                Toast.makeText(this, "文章发布成功", Toast.LENGTH_SHORT).show();
                finish();
                // 发送广播更新列表
                sendBroadcast(new Intent("com.example.qu_tao.UPDATE_POSTS"));
            } else {
                throw new Exception("插入帖子失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "发布失败：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        } finally {
            db.endTransaction(); // 结束事务
            db.close(); // 关闭数据库
        }
    }

    private boolean hasUnsavedChanges() {
        return !TextUtils.isEmpty(etContent.getText().toString().trim());
    }

    private void showExitConfirmationDialog() {
        new AlertDialog.Builder(this)
                .setMessage("是否放弃本次发布？")
                .setPositiveButton("确定", (dialog, which) -> {
                    dialog.dismiss();
                    finish();
                })
                .setNegativeButton("取消", null)
                .setCancelable(false)
                .show();
    }

    @Override
    public void onBackPressed() {
        if (hasUnsavedChanges()) {
            showExitConfirmationDialog();
        } else {
            super.onBackPressed(); // 正常返回
        }
    }
}